<script lang="ts" setup>
import { h, ref, reactive, watch, computed } from 'vue'
import classTeachersEl from './classTeachersEl.vue'
import { useResetReactive } from 'dsrz/hooks/useReset'
import { aesEncrypt, createRef, refs } from 'dsrz/utils'
import type { ColumnItem, Params, FormDetails } from '../types/index'


// 定义 props
const props = defineProps<{
  visible: boolean,
  dialogTitle?: string,
}>()

// 定义 emits
const emit = defineEmits<{
  close: []
  confirm: [data: any]
}>()

const optionList = reactive([
    { label: '王老师', value: 1, id: 1, nickname: '王老师' },
    { label: '张老师', value: 2, id: 2, nickname: '张老师' },
    { label: '王老师1', value: 3, id: 3, nickname: '王老师1' },
    { label: '王老师2', value: 4, id: 4, nickname: '王老师2' },
    { label: '王老师3', value: 5, id: 5, nickname: '王老师3' },
])


// 先定义 details，classTeachers 必须初始化为数组以保持响应式
const formDetails = reactive({
  classTeachers: [] as any[]
} as any)

const editor = (value: any) => {
    if (!value) return
    
    // 清空旧数据（保留 classTeachers）
    Object.keys(formDetails).forEach(key => {
        if (key !== 'classTeachers') {
            delete formDetails[key]
        }
    })
    
    // 批量赋值新数据
    Object.keys(value).forEach(key => {
        if (key === 'classTeachers') {
            // 对于数组，清空后再填充，保持引用不变
            formDetails.classTeachers.length = 0
            const newTeachers = value.classTeachers?.map((item: any) => ({
                id: item.userId,
            })) || []
            formDetails.classTeachers.push(...newTeachers)
        } else if (key === 'headmasterTeachers') {
            formDetails.headmasterTeachers = value.headmasterTeachers?.userId
        } else if (key === 'instructorTeachers') {
            formDetails.fdyid = value.instructorTeachers?.userId
        } else {
            formDetails[key] = value[key]
        }
    })
    
    console.log('== 教师 ', formDetails)
}

const form = reactive({
  size: 'default',
  details: formDetails,
  items: [
    {
      label: '学期',
      prop: 'termName',
      is: 'el-input',
      bind: {
        disabled: true,
      },
    },
    {
      label: '班主任',
      prop: 'headmasterTeachers',
      is: 'currency-select',
      bind: {
        clearable: true,
        placeholder: '请选择班主任',
        options: optionList,
      },
    },
    {
      label: '辅导员',
      prop: 'fdyid',
      is: 'currency-select',
      bind: {
        clearable: true,
        placeholder: '请选择辅导员',
        options: optionList,
      },
    },
    {
      label: '班级教师',
      prop: 'classTeachers',
      is: h(classTeachersEl),
      bind: {
        classTeachers: formDetails.classTeachers,
        tescheListArr: optionList
      },
      on: {
        change: (selectedTeachers: any[]) => {
          console.log('==  选中的班级教师数据:', selectedTeachers)
          formDetails.classTeachers = selectedTeachers
        }
      }
    },

  ],
  rules: {
    headmasterTeachers: [{ required: true, message: '请选择班主任', trigger: 'blur' }],
    fdyid: [{ required: true, message: '请选择辅导员', trigger: 'blur' }],
  },
})


const handleConfirm = async () => {
  // 通过全局 refs 访问表单实例
  const formInstance = refs.formRef

  console.log('获取 教师 form 表单 ', form.details)
  
  if (formInstance) {
    try {
      // 触发表单验证
      await formInstance.validate()
      // 验证通过，执行确认逻辑
      emit('confirm', form.details)
      emit('close') // 通知父组件关闭弹出框
    } catch (error) {
      // 验证失败
      console.log('表单验证失败', error)
      return false // 阻止对话框关闭
    }
  } else {
    console.log('表单实例未找到')
    return false
  }
}

// 重置表单逻辑
const resetForm = () => {
    // 清空表单数据，保持响应式引用
    Object.keys(formDetails).forEach(key => {
        if (key === 'classTeachers') {
            formDetails.classTeachers.length = 0 // 清空数组但保持引用
        } else {
            delete formDetails[key]
        }
    })
    
    // 重置表单验证状态
    const formInstance = refs.formRef
    if (formInstance) {
        formInstance.resetFields()
    }
    
    console.log('重置表单')
}

const cancel = () => {
    resetForm()
    emit('close') // 通知父组件关闭弹出框
}



defineExpose({
  editor,
})
</script>

<template>
    <CurrencyDialog
      v-model="props.visible"
      title="教师管理"
      :size="form.size"
      @cancel="cancel"
      @confirm="handleConfirm"
      >
      <CurrencyForm
        ref="formRef"
        v-model="form.details"
        :items="form.items"
        :rules="form.rules"
        label-position="top"
      />
    </CurrencyDialog>
</template>